package com.ethink.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ethink.framework.common.db.PageUtils;
import com.ethink.system.api.enums.SystemUserEnabledEnum;
import com.ethink.system.api.info.SystemOrganizationInfo;
import com.ethink.system.api.info.SystemRoleInfo;
import com.ethink.system.api.info.SystemUserInfo;
import com.ethink.system.api.request.SystemUserAddRequest;
import com.ethink.system.api.request.SystemUserListRequest;
import com.ethink.system.api.request.SystemUserQueryRequest;
import com.ethink.system.api.request.SystemUserUpdateRequest;
import com.ethink.system.api.response.SystemUserAddResponse;
import com.ethink.system.api.response.SystemUserDeleteResponse;
import com.ethink.system.api.response.SystemUserDetailResponse;
import com.ethink.system.api.response.SystemUserUpdateResponse;
import com.ethink.system.common.entity.SystemUser;
import com.ethink.system.common.entity.SystemUserRole;
import com.ethink.system.common.mapper.SystemUserMapper;
import com.ethink.system.common.mapper.SystemUserOrgMapper;
import com.ethink.system.common.mapper.SystemUserRoleMapper;
import com.ethink.system.common.properties.SystemCommonProperties;
import com.ethink.system.converter.SystemUserConverter;
import com.ethink.system.service.SystemUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 系统用户表 Service接口实现
 *
 * @author default
 * @date 2022-09-26
 */
@Slf4j
@Service
public class SystemUserServiceImpl implements SystemUserService {

    @Autowired
    private SystemCommonProperties commonProperties;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private SystemUserConverter systemUserConverter;

    @Autowired
    private SystemUserRoleMapper systemUserRoleMapper;

    @Autowired
    private SystemUserOrgMapper systemUserOrgMapper;

    @Override
    public Page<SystemUserInfo> querySystemUser(SystemUserQueryRequest request) {
        return systemUserMapper.querySystemUser(PageUtils.buildPage(request), request);
    }

    @Override
    public SystemUserDetailResponse getSystemUserById(Long systemUserId) {
        SystemUserDetailResponse response = new SystemUserDetailResponse();
        SystemUserInfo info = systemUserMapper.getSystemUserById(systemUserId);
        response.setUserInfo(info);
        //获取角色
        List<SystemRoleInfo> roleInfoList = systemUserRoleMapper.selectRoleListByUserId(systemUserId);
        response.setRoleInfoList(roleInfoList);
        //获取组织信息
        List<SystemOrganizationInfo> orgInfoList = systemUserOrgMapper.selectOrgListByUserId(systemUserId);
        response.setOrganizationInfoList(orgInfoList);
        return response;
    }

    @Override
    public List<SystemUserInfo> listSystemUser(SystemUserListRequest request) {
        return systemUserMapper.listSystemUser(request);
    }

    @Override
    public SystemUserAddResponse addSystemUser(SystemUserAddRequest request) {
        SystemUserAddResponse response = new SystemUserAddResponse();
        SystemUser systemUser = new SystemUser();
        BeanUtils.copyProperties(request, systemUser);
        systemUser.setPassword(MD5.create().digestHex(commonProperties.getDefaultPwd()));
        systemUser.setEnabled(SystemUserEnabledEnum.ENABLE.getIntValue());
        systemUserMapper.insert(systemUser);
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SystemUserUpdateResponse updateSystemUser(SystemUserUpdateRequest request) {
        SystemUserUpdateResponse response = new SystemUserUpdateResponse();
        LambdaUpdateWrapper<SystemUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SystemUser::getId, request.getId());
        updateWrapper.set(SystemUser::getRealName, request.getRealName());
        updateWrapper.set(SystemUser::getMobileNo, request.getMobileNo());
        updateWrapper.set(SystemUser::getEmail, request.getEmail());
        updateWrapper.set(SystemUser::getEnabled, request.getEnabled());
        updateWrapper.set(SystemUser::getUserType, request.getUserType());
        updateWrapper.set(SystemUser::getUid, request.getUid());
        updateWrapper.set(SystemUser::getJobNumber, request.getJobNumber());
//        systemUserMapper.update(null, updateWrapper);
        systemUserRoleMapper.delete(new LambdaQueryWrapper<SystemUserRole>().eq(SystemUserRole::getSystemUserId, request.getId()));
        if (CollUtil.isNotEmpty(request.getRoleIds())) {
            SystemUserRole userRole;
            for (Long roleId : request.getRoleIds()) {
                userRole = new SystemUserRole();
                userRole.setRoleId(roleId);
                userRole.setSystemUserId(request.getId());
                systemUserRoleMapper.insert(userRole);
            }
        }
        return response;
    }

    @Override
    public SystemUserInfo savaOrUpdate(SystemUserAddRequest request) {
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getIsDeleted, false)
                .eq(SystemUser::getLoginName, request.getLoginName());
        SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);
        if (systemUser == null) {
            systemUser = new SystemUser();
            BeanUtils.copyProperties(request, systemUser);
            systemUser.setPassword(MD5.create().digestHex(commonProperties.getDefaultPwd()));
            systemUser.setEnabled(SystemUserEnabledEnum.ENABLE.getIntValue());
            systemUser.setLastLoginTime(new Date());
            systemUserMapper.insert(systemUser);
        } else {
            systemUser.setRealName(request.getRealName());
            systemUser.setMobileNo(request.getMobileNo());
            systemUser.setEmail(request.getEmail());
            systemUser.setUid(request.getUid());
            systemUser.setJobNumber(request.getJobNumber());
            systemUser.setLastLoginTime(new Date());
            systemUserMapper.updateById(systemUser);
        }
        return systemUserConverter.convertFrom(systemUser);
    }

    @Override
    public SystemUserDeleteResponse deleteSystemUser(Long systemUserId) {
        SystemUserDeleteResponse response = new SystemUserDeleteResponse();
        LambdaUpdateWrapper<SystemUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SystemUser::getId, systemUserId);
        updateWrapper.set(SystemUser::getIsDeleted, true);
        systemUserMapper.update(null, updateWrapper);
        return response;
    }

    @Override
    public SystemUserInfo getByLoginName(String loginName) {
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getIsDeleted, false)
                .eq(SystemUser::getLoginName, loginName);
        return systemUserConverter.convertFrom(systemUserMapper.selectOne(queryWrapper));
    }

}
